package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.service.WechatService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {
    private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";
    private static final String ACCESSTOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${zzyl.wechat.appid}")
    private String appId;

    @Value("${zzyl.wechat.secret}")
    private String secret;

    @Override
    public String getOpenId(String code) {
        Map<String,Object> requestUrlParam = getAppConfig();
        requestUrlParam.put("js_code",code);
        requestUrlParam.put("grant_type","authorization_code");
        String result = HttpUtil.get(OPENID_URL, requestUrlParam);
        JSONObject jsonObj = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotEmpty(jsonObj.getInt("errcode"))) {
            throw new RuntimeException(jsonObj.getStr("errmsg"));
        }
        return jsonObj.getStr("openid");
    }

    @Override
    public String getPhone(String phoneCode) {
        Map<String,Object> requestParam = new HashMap<>();
        requestParam.put("code",phoneCode);
        String result = HttpUtil.post(PHONE_URL + getAccessToken(),JSONUtil.toJsonStr(requestParam));
        JSONObject jsonObj = JSONUtil.parseObj(result);
        if (jsonObj.getInt("errcode") != 0) {
            //若code不正确，则获取不到phone，响应失败
            throw new RuntimeException(jsonObj.getStr("errmsg"));

        }
        return jsonObj.getJSONObject("phone_info").getStr("purePhoneNumber");
    }

    private String getAccessToken() {
        Map<String, Object> requestParam = getAppConfig();
        requestParam.put("grant_type", "client_credential");
        String result = HttpUtil.get(ACCESSTOKEN_URL, requestParam);
        JSONObject jsonObj = JSONUtil.parseObj(result);
        String accessToken = jsonObj.getStr("access_token");
        if (StringUtils.isEmpty(accessToken)) {
            throw new RuntimeException("token为空");
        }
        return accessToken;
    }

    private Map<String, Object> getAppConfig() {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("appid", appId);
        requestParam.put("secret", secret);
        return requestParam;
    }
}
